﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public static class CodeHelper
    {
        public static string codes;
        //数字验证码
        public static Bitmap GetCode()
        {
            //创建位图画板
            Bitmap bitmap = new Bitmap(140, 40);

            //创建画笔
            Graphics graphics = Graphics.FromImage(bitmap);

            //创建颜色数组
            Color[] colors = { Color.Black, Color.Red, Color.Green, Color.Blue, Color.Coral, Color.HotPink
        };
            Random rand = new Random();

            //清空验证码
            codes = "";

            //创建4位验证码
            for(int i = 0; i < 4; i++)
            {
                String v = rand.Next(0, 10).ToString();
                codes = codes + v;
                graphics.DrawString(v, new Font("楷体" , 16f), new SolidBrush(colors[rand.Next(0, 6)]), new PointF(i * 15 + 7, rand.Next(0, 8)));
            }

            //绘制10条干扰线
            for(int i = 0; i < 10; i++)
            {
                graphics.DrawLine(new Pen(colors[rand.Next(0, 6)], 1), rand.Next(0, bitmap.Width) , rand.Next(0, bitmap.Height),
                    rand.Next(0, bitmap.Width), rand.Next(0, bitmap.Height));
            }

            // 绘制噪声500个点
            for(int i = 0; i < 500; i++)
            {
                bitmap.SetPixel(rand.Next(0, bitmap.Width), rand.Next(0, bitmap.Height), colors[rand.Next(0, 6)]);
            }

            return bitmap;
        }
    }
}
